import axios from "axios";
import md5 from "js-md5";
import router from "@/router/index.js";
import {useTokenStore} from "@/store/user.js";
import constant from "@/utils/constant.js";
import {ElNotification, ElMessageBox, ElLoading} from "element-plus";

const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000,
});

let loading = null;

request.interceptors.request.use(config => {
    // 加载loading
    loading = ElLoading.service({
        lock: true,
        text: "Loading...",
        background: "rgba(0, 0, 0, 0.7)",
    });
    const tokenStore = useTokenStore();
    let token = "LN8THdq0tagV/AwUImaHOcNmh3+DU6G8vr5bF44TX8niEyeOWVFz2xKCVbuZaF5JomFsEYs2U4eg==";
    if (tokenStore.token) {
        token = tokenStore.token;
        config.headers.set("Authorization", "Bearer " + tokenStore.token, false);
        config.headers.set("Token", token, false);
    }
    const time = Math.round(new Date().getTime() / 1000);
    const Sign = `${time}&${constant.appKey}&${token}&${constant.cryptojs_key}`;
    config.headers.set("Time", time, false);
    config.headers.set("Sign", (md5(Sign)).toUpperCase(), false);
    return config;
}, error => {
    return Promise.reject(error);
});

let CODE_SYS_ERROR = 0;

request.interceptors.response.use(response => {
    const res = response.data;
    if (response.status !== 200 || (res.code && res.code !== 200)) {
        loading.close();
        return response.data;
    } else {
        loading.close();
        return response.data;
    }
}, error => {
    const tokenStore = useTokenStore();
    if (error.message === "Network Error") {
        CODE_SYS_ERROR += 1;
        if (CODE_SYS_ERROR === 1) {
            // 执行一次
            ElNotification.warning(`服务器请求失败`);
        }
    } else if (!tokenStore.token) {
        ElNotification.warning("当前会话未建立，请先登录");
    }
    loading.close();
    return Promise.reject(error);
});

export default request;